package edu.scau.mis.web.aspect;

import edu.scau.mis.core.annotation.RequestLog;
import edu.scau.mis.core.domain.AjaxResult;
import edu.scau.mis.core.utils.ServletUtils;
import edu.scau.mis.system.domain.Log;
import edu.scau.mis.system.security.utils.SecurityUtils;
import edu.scau.mis.system.service.ILogService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Date;

/**
 * Controller接口请求日志切面
 */
@Aspect
@Component
public class RequestLoggerAspect {
    private Logger logger= LoggerFactory.getLogger(RequestLoggerAspect.class);

    @Autowired
    private ILogService logService;

    /**
     * 定义切入点
     */
    @Pointcut(value = "execution( * edu.scau.mis.*.controller..*.*(..))")

    public void logPointcut(){
    }

    /**
     * 执行AfterReturning通知
     * @param joinPoint
     * @param ajaxResult
     * @throws Throwable
     */

    @AfterReturning(pointcut = "logPointcut()", returning = "ajaxResult")

    public void doAfterReturningAdvice(JoinPoint joinPoint, Object ajaxResult) throws Throwable {
        RequestLog requestLog = getAnnotationLog(joinPoint);
        if (requestLog == null) {
            return;
        }
        AjaxResult result = (AjaxResult) ajaxResult;
        String className = joinPoint.getTarget().getClass().toString();
        String methodName = joinPoint.getSignature().getName();
        String requestUrl = ServletUtils.getRequest().getRequestURI();
        String requestMethod = ServletUtils.getRequest().getMethod();
        Log log = new Log();
        log.setTarget(className);
        log.setMethod(methodName);
        log.setRequestUrl(requestUrl);
        log.setRequestMethod(requestMethod);
        log.setTitle(requestLog.title());
        log.setBusinessType(requestLog.businessType().toString());
        log.setResultCode((Integer) result.get("code"));
        log.setRequestBy(SecurityUtils.getUsername());
        log.setRequestTime(new Date());

        logService.insert(log);
    }

    /**
     * 是否切入点方法上是否存在注解，如果存在就获取
     */
    private RequestLog getAnnotationLog(JoinPoint joinPoint) throws Exception {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        if (method != null) {
            return method.getAnnotation(RequestLog.class);
        }
        return null;
    }
}
